<template>
  <div class="monthly-plans">
    <div class="header">
      <h3>月度工作计划</h3>
      <div class="header-actions">
        <!-- 年度计划筛选 -->
        <el-select 
          v-model="selectedAnnualPlan" 
          placeholder="选择年度计划" 
          style="width: 200px; margin-right: 10px;"
          @change="filterMonthlyPlans"
        >
          <el-option label="全部年度计划" value="" />
          <el-option 
            v-for="plan in annualPlans" 
            :key="plan.id" 
            :label="`${plan.year}年 - ${plan.title}`" 
            :value="plan.id" 
          />
        </el-select>
        
        <el-button type="primary" @click="openCreateDialog">创建月度计划</el-button>
        <el-button type="success" @click="showAISuggestionDialog = true">
          <el-icon><MagicStick /></el-icon> AI 月度建议
        </el-button>
        <el-button type="danger" @click="batchDelete" :disabled="selectedPlans.length === 0">
          <el-icon><Delete /></el-icon> 批量删除 ({{ selectedPlans.length }})
        </el-button>
        <el-button @click="toggleSelectAll">
          {{ selectedPlans.length === filteredPlans.length && filteredPlans.length > 0 ? '取消全选' : '全选' }}
        </el-button>
      </div>
    </div>

    <!-- 创建/编辑月度计划对话框 -->
    <el-dialog v-model="showCreateDialog" :title="isEdit ? '编辑月度计划' : '创建月度计划'" width="600px">
      <el-form :model="newPlan" :rules="rules" ref="planFormRef" label-width="100px">
        <el-form-item label="月份" prop="planDate">
          <el-date-picker
            v-model="planDate"
            type="month"
            placeholder="选择月份"
            format="YYYY年MM月"
            value-format="YYYY-MM"
            @change="handleDateChange"
            style="width: 100%"
          />
        </el-form-item>
        
        <el-form-item label="标题" prop="title">
          <el-input v-model="newPlan.title" placeholder="请输入计划标题" />
        </el-form-item>
        
        <el-form-item label="描述" prop="description">
          <el-input v-model="newPlan.description" type="textarea" :rows="3" placeholder="请输入计划描述" />
        </el-form-item>
        
        <el-form-item label="目标" prop="objectives">
          <el-input v-model="newPlan.objectives" type="textarea" :rows="4" placeholder="请输入具体目标和指标" />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showCreateDialog = false">取消</el-button>
        <el-button type="primary" @click="submitPlan" :loading="loading">{{ isEdit ? '更新' : '创建' }}</el-button>
      </template>
    </el-dialog>

    <!-- 计划列表 (卡片视图) -->
    <div v-if="loading" class="loading-container">
      <el-skeleton :rows="3" animated />
    </div>
    
    <div v-else-if="filteredPlans.length === 0" class="empty-state">
      <el-empty description="暂无月度计划" />
    </div>

    <el-row v-else :gutter="20" class="plan-grid">
      <el-col 
        v-for="plan in filteredPlans" 
        :key="plan.id" 
        :xs="24" 
        :sm="12" 
        :md="8" 
        :lg="8" 
        :xl="6"
      >
        <el-card 
          class="plan-card" 
          :class="{ 'is-selected': selectedPlans.includes(plan.id) }"
          shadow="hover"
          @click.stop="toggleSelection(plan.id)"
        >
          <template #header>
            <div class="card-header">
              <div class="header-left">
                <el-checkbox 
                  :model-value="selectedPlans.includes(plan.id)"
                  @change="toggleSelection(plan.id)"
                  @click.stop
                />
                <span class="plan-date">{{ plan.year }}年{{ plan.month }}月</span>
              </div>
              <el-tag :type="getStatusType(plan.status)" size="small" effect="dark">
                {{ getStatusText(plan.status) }}
              </el-tag>
            </div>
          </template>
          
          <div class="card-content">
            <h4 class="plan-title" :title="plan.title">{{ plan.title }}</h4>
            
            <div class="plan-section">
              <div class="section-label">计划描述</div>
              <div class="section-text description" :class="{ 'empty': !plan.description }">
                {{ plan.description || '暂无描述内容，请点击编辑补充' }}
              </div>
            </div>
            
            <div class="plan-section">
              <div class="section-label">目标摘要</div>
              <div class="section-text objectives">
                {{ plan.objectives || '暂无具体目标' }}
              </div>
            </div>
            
            <div class="plan-meta">
              <span>创建于: {{ formatDate(plan.created_at).split(' ')[0] }}</span>
            </div>
          </div>
          
          <div class="card-actions" @click.stop>
            <el-tooltip content="查看详情" placement="top">
              <el-button circle size="small" @click="viewPlan(plan)">
                <el-icon><View /></el-icon>
              </el-button>
            </el-tooltip>
            
            <el-tooltip content="编辑计划" placement="top">
              <el-button circle size="small" type="warning" @click="editPlan(plan)">
                <el-icon><Edit /></el-icon>
              </el-button>
            </el-tooltip>
            
            <el-tooltip content="更新状态" placement="top">
              <el-button circle size="small" type="primary" @click="updateStatus(plan)">
                <el-icon><Refresh /></el-icon>
              </el-button>
            </el-tooltip>
            
            <el-tooltip content="生成周计划" placement="top">
              <el-button circle size="small" type="success" @click="generateWeeklyPlans(plan)">
                <el-icon><Calendar /></el-icon>
              </el-button>
            </el-tooltip>

            <el-tooltip content="一键生成月报" placement="top">
              <el-button circle size="small" type="warning" @click="handleGenerateMonthlyReport(plan)">
                <el-icon><DocumentCopy /></el-icon>
              </el-button>
            </el-tooltip>
            
            <el-tooltip content="删除计划" placement="top">
              <el-button circle size="small" type="danger" @click="deletePlan(plan)">
                <el-icon><Delete /></el-icon>
              </el-button>
            </el-tooltip>
          </div>
        </el-card>
      </el-col>
    </el-row>

    <!-- 计划详情对话框 -->
    <el-dialog v-model="showDetailDialog" :title="currentPlan?.title" width="700px">
      <div v-if="currentPlan">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="年份">{{ currentPlan.year }}</el-descriptions-item>
          <el-descriptions-item label="月份">{{ getMonthName(currentPlan.month) }}</el-descriptions-item>
          <el-descriptions-item label="状态">
            <el-tag :type="getStatusType(currentPlan.status)">{{ getStatusText(currentPlan.status) }}</el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="创建时间">{{ formatDate(currentPlan.created_at) }}</el-descriptions-item>
        </el-descriptions>
        
        <el-divider>计划描述</el-divider>
        <p>{{ currentPlan.description }}</p>
        
        <el-divider>具体目标</el-divider>
        <p>{{ currentPlan.objectives }}</p>

        <el-divider>周计划执行情况 (关联指标)</el-divider>
        <div v-loading="loadingWeeklyPlans">
          <el-empty v-if="weeklyPlans.length === 0" description="该月暂无周计划" />
          <el-table v-else :data="weeklyPlans" style="width: 100%" border stripe>
            <el-table-column prop="week" label="周次" width="80" align="center">
              <template #default="{ row }">第 {{ row.week }} 周</template>
            </el-table-column>
            <el-table-column prop="title" label="计划标题" width="180" show-overflow-tooltip />
            <el-table-column prop="objectives" label="关联指标/目标" show-overflow-tooltip />
            <el-table-column prop="status" label="状态" width="100" align="center">
              <template #default="{ row }">
                <el-tag :type="getStatusType(row.status)" size="small">{{ getStatusText(row.status) }}</el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
    </el-dialog>

    <!-- 更新状态对话框 -->
    <el-dialog v-model="showStatusDialog" title="更新计划状态" width="400px">
      <el-form :model="statusForm">
        <el-form-item label="状态">
          <el-select v-model="statusForm.status" placeholder="选择状态">
            <el-option label="待开始" value="pending" />
            <el-option label="进行中" value="in_progress" />
            <el-option label="已完成" value="completed" />
          </el-select>
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showStatusDialog = false">取消</el-button>
        <el-button type="primary" @click="confirmStatusUpdate">确认</el-button>
      </template>
    </el-dialog>

    <!-- AI 月度建议对话框 -->
    <el-dialog
      v-model="showAISuggestionDialog"
      title="AI 月度计划建议"
      width="700px"
    >
      <el-form :model="aiSuggestionForm" label-width="120px">
        <el-form-item label="基于年度计划">
          <el-select 
            v-model="aiSuggestionForm.annualPlanId" 
            placeholder="选择年度计划（可选）"
            :loading="loadingAnnualPlans"
            clearable
          >
            <el-option
              v-for="plan in annualPlans"
              :key="plan.id"
              :label="`${plan.year}年 - ${plan.title}`"
              :value="plan.id"
            />
          </el-select>
        </el-form-item>
        
        <el-form-item label="或自定义目标">
          <el-input 
            v-model="aiSuggestionForm.customGoal" 
            type="textarea" 
            :rows="4"
            placeholder="请详细描述您的工作目标和期望达成的成果..."
          />
        </el-form-item>
        
        <el-form-item label="关键指标">
          <el-input 
            v-model="aiSuggestionForm.keyMetrics" 
            type="textarea" 
            :rows="3"
            placeholder="请列出可量化的关键指标（如：销售额增长20%，客户满意度达到90%等）"
          />
        </el-form-item>
        
        <el-form-item label="时间范围">
          <el-date-picker
            v-model="aiSuggestionForm.timeframe"
            type="monthrange"
            range-separator="至"
            start-placeholder="开始月份"
            end-placeholder="结束月份"
            format="YYYY年MM月"
            value-format="YYYY-MM"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="showAISuggestionDialog = false">取消</el-button>
        <el-button 
          type="primary" 
          @click="generateAISuggestion" 
          :loading="generatingAISuggestion"
        >
          <el-icon><MagicStick /></el-icon>
          生成月度计划建议
        </el-button>
      </template>
    </el-dialog>

    <!-- AI 月度建议确认对话框 -->
    <el-dialog
      v-model="showAIConfirmDialog"
      title="AI 月度建议确认"
      width="800px"
    >
      <div v-if="aiSuggestionResult" class="ai-confirm-content">
        <h4>月度计划建议概览</h4>
        <el-table :data="aiSuggestionResult.monthlyPlans" height="400">
          <el-table-column prop="month" label="月份" width="100" />
          <el-table-column prop="mainObjective" label="月度目标" width="200" />
          <el-table-column prop="tasks" label="任务数量">
            <template #default="{ row }">
              {{ row.tasks?.length || 0 }} 个任务
            </template>
          </el-table-column>
          <el-table-column prop="metrics" label="关键指标">
            <template #default="{ row }">
              {{ row.metrics?.map(m => m.target).join('，') || '' }}
            </template>
          </el-table-column>
        </el-table>

        <h4 style="margin-top: 20px;">第一个月详细任务</h4>
        <div v-if="aiSuggestionResult.monthlyPlans[0]">
          <el-table :data="aiSuggestionResult.monthlyPlans[0].tasks" height="200">
            <el-table-column prop="week" label="周次" width="80" />
            <el-table-column prop="title" label="任务标题" width="200" />
            <el-table-column prop="description" label="任务描述" />
            <el-table-column prop="priority" label="优先级" width="100">
              <template #default="{ row }">
                <el-tag :type="getPriorityType(row.priority)">
                  {{ getPriorityText(row.priority) }}
                </el-tag>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </div>
      
      <template #footer>
        <el-button @click="regenerateAISuggestion">重新生成</el-button>
        <el-button type="primary" @click="confirmAISuggestion">确认使用</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { useAuthStore } from '../stores/auth'
import { MagicStick, Delete, View, Edit, Refresh, Calendar, DocumentCopy } from '@element-plus/icons-vue'

export default {
  name: 'MonthlyPlans',
  components: {
    MagicStick,
    Delete,
    View,
    Edit,
    Refresh,
    Calendar,
    DocumentCopy
  },
  setup() {
    const authStore = useAuthStore()
    const plans = ref([])
    const filteredPlans = ref([])
    const annualPlans = ref([])
    const loading = ref(false)
    const loadingAnnualPlans = ref(false)
    const selectedPlans = ref([])
    const selectedAnnualPlan = ref('')
    const showCreateDialog = ref(false)
    const showAISuggestionDialog = ref(false)
    const showAIConfirmDialog = ref(false)
    const showDetailDialog = ref(false)
    const showStatusDialog = ref(false)
    const currentPlan = ref(null)
    const planFormRef = ref()
    const generatingAISuggestion = ref(false)
    const aiSuggestionResult = ref(null)
    const isEdit = ref(false)
    const editingId = ref(null)
    const planDate = ref('')

    // New refs for weekly plans association
    const weeklyPlans = ref([])
    const loadingWeeklyPlans = ref(false)

    const newPlan = ref({
      year: new Date().getFullYear(),
      month: new Date().getMonth() + 1,
      title: '',
      description: '',
      objectives: ''
    })

    const aiSuggestionForm = ref({
      annualPlanId: '',
      customGoal: '',
      keyMetrics: '',
      timeframe: [
        `${new Date().getFullYear()}-${String(new Date().getMonth() + 1).padStart(2, '0')}`,
        `${new Date().getFullYear()}-${String(new Date().getMonth() + 1).padStart(2, '0')}`
      ]
    })

    const statusForm = ref({
      status: ''
    })

    const years = ref([2023, 2024, 2025, 2026])
    const months = ref([
      { label: '一月', value: 1 }, { label: '二月', value: 2 }, { label: '三月', value: 3 },
      { label: '四月', value: 4 }, { label: '五月', value: 5 }, { label: '六月', value: 6 },
      { label: '七月', value: 7 }, { label: '八月', value: 8 }, { label: '九月', value: 9 },
      { label: '十月', value: 10 }, { label: '十一月', value: 11 }, { label: '十二月', value: 12 }
    ])

    const rules = {
      title: [{ required: true, message: '请输入标题', trigger: 'blur' }]
    }

    const handleDateChange = (val) => {
      if (val) {
        const [y, m] = val.split('-')
        newPlan.value.year = parseInt(y)
        newPlan.value.month = parseInt(m)
      }
    }

    const getMonthName = (month) => {
      const monthObj = months.value.find(m => m.value === month)
      return monthObj ? monthObj.label : ''
    }

    const getStatusType = (status) => {
      const types = {
        pending: 'info',
        in_progress: 'warning',
        completed: 'success'
      }
      return types[status] || 'info'
    }

    const getStatusText = (status) => {
      const texts = {
        pending: '待开始',
        in_progress: '进行中',
        completed: '已完成'
      }
      return texts[status] || status
    }

    const getPriorityType = (priority) => {
      const types = {
        high: 'danger',
        medium: 'warning',
        low: 'success'
      }
      return types[priority] || 'info'
    }

    const getPriorityText = (priority) => {
      const texts = {
        high: '高优先级',
        medium: '中优先级',
        low: '低优先级'
      }
      return texts[priority] || priority
    }

    const formatDate = (dateString) => {
      return new Date(dateString).toLocaleString('zh-CN')
    }

    const fetchPlans = async () => {
      loading.value = true
      try {
        const response = await axios.get('/api/plans/monthly', {
          headers: { Authorization: `Bearer ${authStore.token}` }
        })
        plans.value = response.data
        filterMonthlyPlans() // 初始筛选
      } catch (error) {
        ElMessage.error('获取月度计划失败')
      } finally {
        loading.value = false
      }
    }

    // 根据年度计划筛选月度计划
    const filterMonthlyPlans = () => {
      if (!selectedAnnualPlan.value) {
        filteredPlans.value = plans.value
      } else {
        // 根据年度计划ID筛选月度计划
        filteredPlans.value = plans.value.filter(plan => plan.annual_plan_id === selectedAnnualPlan.value)
      }
    }

    const fetchAnnualPlans = async () => {
      loadingAnnualPlans.value = true
      try {
        const response = await axios.get('/api/plans/annual', {
          headers: { Authorization: `Bearer ${authStore.token}` }
        })
        annualPlans.value = response.data
      } catch (error) {
        ElMessage.error('获取年度计划失败')
      } finally {
        loadingAnnualPlans.value = false
      }
    }

    const openCreateDialog = () => {
      isEdit.value = false
      editingId.value = null
      resetForm()
      // Set default date to current month
      const now = new Date()
      planDate.value = `${now.getFullYear()}-${String(now.getMonth() + 1).padStart(2, '0')}`
      handleDateChange(planDate.value)
      showCreateDialog.value = true
    }

    const editPlan = (plan) => {
      isEdit.value = true
      editingId.value = plan.id
      newPlan.value = {
        year: plan.year,
        month: plan.month,
        title: plan.title,
        description: plan.description,
        objectives: plan.objectives
      }
      // Set planDate for the picker
      planDate.value = `${plan.year}-${String(plan.month).padStart(2, '0')}`
      showCreateDialog.value = true
    }

    const submitPlan = async () => {
      if (!planFormRef.value) return
      
      // 先验证日期
      if (!planDate.value) {
        ElMessage.warning('请选择月份')
        return
      }
      
      await planFormRef.value.validate(async (valid) => {
        if (valid) {
          loading.value = true
          try {
            if (isEdit.value) {
              await axios.put(`/api/plans/monthly/${editingId.value}`, newPlan.value, {
                headers: { Authorization: `Bearer ${authStore.token}` }
              })
              ElMessage.success('月度计划更新成功')
            } else {
              await axios.post('/api/plans/monthly', newPlan.value, {
                headers: { Authorization: `Bearer ${authStore.token}` }
              })
              ElMessage.success('月度计划创建成功')
            }
            showCreateDialog.value = false
            resetForm()
            fetchPlans()
          } catch (error) {
            ElMessage.error(isEdit.value ? '更新月度计划失败' : '创建月度计划失败')
          } finally {
            loading.value = false
          }
        }
      })
    }

    const fetchWeeklyPlans = async (year, month) => {
      loadingWeeklyPlans.value = true
      weeklyPlans.value = []
      try {
        const response = await axios.get('/api/plans/weekly', {
          headers: { Authorization: `Bearer ${authStore.token}` }
        })
        // Filter by year and month
        weeklyPlans.value = response.data.filter(p => p.year === year && p.month === month)
      } catch (error) {
        console.error('获取周计划失败:', error)
        ElMessage.warning('无法获取关联的周计划')
      } finally {
        loadingWeeklyPlans.value = false
      }
    }

    const viewPlan = (plan) => {
      currentPlan.value = plan
      showDetailDialog.value = true
      fetchWeeklyPlans(plan.year, plan.month)
    }

    const updateStatus = (plan) => {
      currentPlan.value = plan
      statusForm.value.status = plan.status
      showStatusDialog.value = true
    }

    const confirmStatusUpdate = async () => {
      if (!statusForm.value.status) {
        ElMessage.warning('请选择状态')
        return
      }
      try {
        await axios.put(`/api/plans/monthly/${currentPlan.value.id}/status`,
          { status: statusForm.value.status },
          { headers: { Authorization: `Bearer ${authStore.token}` } }
        )
        ElMessage.success('状态更新成功')
        showStatusDialog.value = false
        fetchPlans()
      } catch (error) {
        ElMessage.error('状态更新失败')
      }
    }

    const deletePlan = async (plan) => {
      try {
        await ElMessageBox.confirm(
          `确定要删除月度计划 "${plan.title}" 吗？此操作不可恢复。`,
          '确认删除',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
        
        await axios.delete(`/api/plans/monthly/${plan.id}`, {
          headers: { Authorization: `Bearer ${authStore.token}` }
        })

        ElMessage.success('删除成功')
        fetchPlans()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('删除失败')
        }
      }
    }

    const toggleSelection = (id) => {
      const index = selectedPlans.value.indexOf(id)
      if (index > -1) {
        selectedPlans.value.splice(index, 1)
      } else {
        selectedPlans.value.push(id)
      }
    }

    const toggleSelectAll = () => {
      if (selectedPlans.value.length === filteredPlans.value.length) {
        selectedPlans.value = []
      } else {
        selectedPlans.value = filteredPlans.value.map(p => p.id)
      }
    }

    const batchDelete = async () => {
      try {
        await ElMessageBox.confirm(
          `确定要删除选中的 ${selectedPlans.value.length} 个月度计划吗？此操作不可恢复。`,
          '批量删除确认',
          {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning',
          }
        )
        
        await Promise.all(
          selectedPlans.value.map(id =>
            axios.delete(`/api/plans/monthly/${id}`, {
              headers: { Authorization: `Bearer ${authStore.token}` }
            })
          )
        )

        ElMessage.success('批量删除成功')
        selectedPlans.value = []
        fetchPlans()
      } catch (error) {
        if (error !== 'cancel') {
          ElMessage.error('批量删除失败')
        }
      }
    }

    const generateWeeklyPlans = async (plan) => {
      try {
        const loading = ElMessage({
          message: '正在生成周计划...',
          type: 'info',
          duration: 0
        })

        const response = await axios.post('/api/plans/weekly/generate-from-monthly', {
          monthlyPlanId: plan.id
        }, {
          headers: { Authorization: `Bearer ${authStore.token}` }
        })

        loading.close()
        ElMessage.success(`成功生成 ${response.data.generated} 个周计划`)
      } catch (error) {
        ElMessage.error('生成周计划失败')
      }
    }

    const handleGenerateMonthlyReport = async (plan) => {
      const targetYear = plan ? plan.year : new Date().getFullYear()
      const targetMonth = plan ? plan.month : new Date().getMonth() + 1

      try {
        // 1. Check if we have enough weekly reports
        const response = await axios.get('/api/reports/weekly', {
          params: { year: targetYear, month: targetMonth },
          headers: { Authorization: `Bearer ${authStore.token}` }
        })
        
        const weeklyReports = response.data.filter(r => r.month === targetMonth && r.year === targetYear)

        if (weeklyReports.length < 4) {
          try {
            await ElMessageBox.confirm(
              `${targetYear}年${targetMonth}月只有 ${weeklyReports.length} 份周报。通常需要 4 份周报才能生成完整的月度总结。是否仍要继续？`,
              '周报数量不足',
              {
                confirmButtonText: '继续生成',
                cancelButtonText: '取消',
                type: 'warning'
              }
            )
          } catch (e) {
            return // User cancelled
          }
        }

        // 2. Proceed to generate
        const loadingMsg = ElMessage({
          message: '正在生成月度报告...',
          type: 'info',
          duration: 0
        })

        await axios.post('/api/reports/monthly/generate', {
          year: targetYear,
          month: targetMonth
        }, {
          headers: { Authorization: `Bearer ${authStore.token}` }
        })

        loadingMsg.close()
        ElMessage.success('月度报告生成成功！请前往"月度工作总结"页面查看。')
        
      } catch (error) {
        console.error('生成月报失败:', error)
        if (error.response) {
          ElMessage.error(`生成月报失败: ${error.response.data.error || '服务器错误'}`)
        } else {
          ElMessage.error('生成月报失败，请检查网络连接')
        }
      }
    }

    const generateAISuggestion = async () => {
      generatingAISuggestion.value = true
      try {
        const response = await axios.post('/api/ai/monthly-suggestions', aiSuggestionForm.value, {
          headers: { Authorization: `Bearer ${authStore.token}` }
        })

        // 保存AI建议结果并显示确认对话框
        aiSuggestionResult.value = response.data
        showAISuggestionDialog.value = false
        showAIConfirmDialog.value = true

      } catch (error) {
        console.error('AI建议生成错误:', error)
        if (error.response) {
          ElMessage.error(`AI建议生成失败: ${error.response.data.error || '服务器错误'}`)
        } else if (error.request) {
          ElMessage.error('网络连接失败，请检查网络连接')
        } else {
          ElMessage.error('AI建议生成失败，请稍后重试')
        }
      } finally {
        generatingAISuggestion.value = false
      }
    }

    const confirmAISuggestion = async () => {
      // 使用第一个月的计划填充表单
      const firstMonthPlan = aiSuggestionResult.value.monthlyPlans[0]
      const monthParts = firstMonthPlan.month.split('-')

      newPlan.value = {
        year: parseInt(monthParts[0]),
        month: parseInt(monthParts[1]),
        title: firstMonthPlan.mainObjective,
        description: firstMonthPlan.tasks.map(t => t.title).join('；'),
        objectives: firstMonthPlan.metrics ? firstMonthPlan.metrics.map(m => m.target).join('，') : ''
      }

      showAIConfirmDialog.value = false
      showCreateDialog.value = true
      ElMessage.success('AI月度计划建议已确认，请查看并完善')
    }

    const regenerateAISuggestion = async () => {
      showAIConfirmDialog.value = false
      showAISuggestionDialog.value = true
    }

    const resetForm = () => {
      newPlan.value = {
        year: new Date().getFullYear(),
        month: new Date().getMonth() + 1,
        title: '',
        description: '',
        objectives: ''
      }
    }

    onMounted(() => {
      fetchPlans()
      fetchAnnualPlans()
    })

    return {
      plans,
      annualPlans,
      filteredPlans,
      loading,
      loadingAnnualPlans,
      selectedPlans,
      selectedAnnualPlan,
      showCreateDialog,
      showAISuggestionDialog,
      showAIConfirmDialog,
      showDetailDialog,
      showStatusDialog,
      currentPlan,
      newPlan,
      aiSuggestionForm,
      aiSuggestionResult,
      statusForm,
      years,
      months,
      rules,
      planFormRef,
      isEdit,
      editingId,
      planDate,
      handleDateChange,
      getMonthName,
      getStatusType,
      getStatusText,
      getPriorityType,
      getPriorityText,
      formatDate,
      submitPlan,
      openCreateDialog,
      editPlan,
      viewPlan,
      updateStatus,
      confirmStatusUpdate,
      deletePlan,
      toggleSelection,
      toggleSelectAll,
      batchDelete,
      generateWeeklyPlans,
      handleGenerateMonthlyReport,
      filterMonthlyPlans,
      weeklyPlans,
      loadingWeeklyPlans,
      generatingAISuggestion,
      generateAISuggestion,
      confirmAISuggestion,
      regenerateAISuggestion,
      resetForm
    }
  }
}
</script>

<style scoped>
.monthly-plans {
  padding: 20px;
}

.header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
  padding: 10px;
  background: #fff;
  border-radius: 4px;
  box-shadow: 0 2px 8px rgba(0,0,0,0.1);
}

.header h3 {
  margin: 0;
  color: #303133;
}

.header-actions {
  display: flex;
  gap: 10px;
  flex-wrap: wrap;
}

.loading-container {
  padding: 40px;
  background: #fff;
  border-radius: 4px;
}

.empty-state {
  padding: 60px;
  background: #fff;
  border-radius: 4px;
  text-align: center;
}

.plan-grid {
  margin-top: 20px;
}

.plan-card {
  margin-bottom: 20px;
  cursor: pointer;
  transition: all 0.3s;
  height: 100%;
}

.plan-card.is-selected {
  border: 2px solid #409EFF;
  box-shadow: 0 4px 12px rgba(64, 158, 255, 0.3);
}

.plan-card:hover {
  transform: translateY(-4px);
  box-shadow: 0 6px 16px rgba(0,0,0,0.15);
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 8px;
}

.plan-date {
  font-size: 14px;
  font-weight: 600;
  color: #606266;
}

.card-content {
  padding: 8px 0;
}

.plan-title {
  margin: 0 0 12px 0;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

.plan-section {
  margin-bottom: 12px;
}

.section-label {
  font-size: 12px;
  color: #909399;
  margin-bottom: 4px;
}

.section-text {
  font-size: 14px;
  color: #606266;
  line-height: 1.6;
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.section-text.empty {
  color: #C0C4CC;
  font-style: italic;
}

.plan-meta {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #EBEEF5;
  font-size: 12px;
  color: #909399;
}

.card-actions {
  display: flex;
  gap: 8px;
  justify-content: center;
  flex-wrap: wrap;
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #EBEEF5;
}

.ai-confirm-content h4 {
  margin-top: 0;
  margin-bottom: 16px;
  color: #303133;
}
</style>